class FireworkNightsky {
    constructor(domRoot) {
        this.nightsky = domRoot
        this.nsWidth = this.nightsky.clientWidth
        this.nsHeight = this.nightsky.clientHeight

        // 添加点击事件
        this.bindEvents()
    }

    // 创建一朵烟花
    createFire(left, top) {
        const fire = document.createElement("span")
        fire.className = "fire"
        fire.style.left = left
        fire.style.top = top
        fire.style.backgroundColor = getRandomColor()
        this.nightsky.appendChild(fire)
        return fire
    }

    // 烟花飞溅
    splash(n, { x, y }, timecost = 500) {
        for (let i = 0; i < n; i++) {
            const f = this.createFire(x, y)
            animate(
                f,
                {
                    left: getRandom(0, this.nsWidth) + "px",
                    top: getRandom(0, this.nsHeight) + "px",
                    alpha: 0
                },
                timecost,
                () => {
                    f.remove()
                })
        }
    }

    bindEvents() {
        this.nightsky.onclick = (e) => {
            // 在夜空底部出现一朵烟花
            const fire = this.createFire(e.offsetX + "px", this.nsHeight + "px")

            // 升空
            animate(fire, { top: e.offsetY + "px" }, 500, () => {
                fire.remove()

                // 造一堆烟花
                this.splash(getRandom(20, 50), { x: e.offsetX + "px", y: e.offsetY + "px" })
            })
        }
    }

}

